const Http = function (url, param = {}) {
  return Http.get(url, param)
}

Http.__proto__.root = ''

Http.__proto__.headers = {
  'Content-Type': 'application/json',
}

Http.__proto__.get = function (url, param = {}, options = {}) {
  url = Http.root + url

  return new Promise((resolve, reject) => {
    if (param) {
      url += '?' + this.parseParam(param)
    }

    fetch(url, {
      method: 'GET',
      headers: {
        ...this.headers,
        ...options,
      },
    })
      .then(async (response) => {
        Http.responseHandle(response, resolve, reject)
      })
      .catch((err) => {
        reject(err)
        Http.errorHandle(err)
      })
  })
}

Http.__proto__.post = function (url, body = {}, options = {}) {
  url = Http.root + url

  if (!(body instanceof FormData)) {
    body = JSON.stringify(body)
  }

  return new Promise((resolve, reject) => {
    fetch(url, {
      method: 'POST',
      body: body,
      headers: {
        ...this.headers,
        ...options,
      },
    })
      .then((response) => {
        Http.responseHandle(response, resolve, reject)
      })
      .catch((err) => {
        reject(err)
        Http.errorHandle(err)
      })
  })
}

Http.__proto__.parseParam = function (param = {}) {
  let query = []
  for (const key in param) {
    if (Object.hasOwnProperty.call(param, key)) {
      query.push(`${key}=${param[key]}`)
    }
  }

  return query.length > 0 ? `${query.join('&')}` : ''
}

/**
 *
 * @param {*} response
 * @param {*} resolve
 * @param {*} reject
 * @returns
 */
Http.__proto__.responseHandle = async function (response, resolve, reject) {
  if (response.status >= 300) {
    throw response
  }

  let data = await response.json()
  if (data.code === 403) {
    reject(data)
    location.href = '/login.html'
    return
  }

  resolve(data)
}

Http.__proto__.errorHandle = function (error) {
  if (error.status === 404) {
    ElMessage.error('资源未找到！')
  } else if (error.status >= 500) {
    ElMessage.error('服务器错误！')
  } else {
    ElMessage.error('请求失败！')
  }
}

export default Http
